package com.heima.commnet.service.impl;

import com.heima.apis.user.IUserClient;

import com.heima.apis.wemedia.IWeMediaClient;
import com.heima.commnet.service.CommentRepayService;
import com.heima.model.article.dtos.ArticleCommentDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.ApCommentRepay;
import com.heima.model.wemedia.pojos.ApCommentRepayLike;
import com.heima.model.wemedia.pojos.WmNewsComment;
import com.heima.model.wemedia.vo.CommentRepayVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import thread.AppThreadLocalUtil;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private IUserClient userClient;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 加载回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadRepay(ArticleCommentDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //数据处理
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(10);
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);

        //数据封装返回
        //用户未登录
        ApUser user = AppThreadLocalUtil.getApUser();
        if (user == null) {
            return ResponseResult.okResult(list);
        }

        //登录了,高亮展示用户点赞
        //当前评论中,被点赞的评论+用户id都一致 高亮
        List<String> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        if (apCommentRepayLikes.size() == 0) {
            return ResponseResult.okResult(list);
        }
        //登录用户点赞的评论 operation设置为0
        List<CommentRepayVo> resultList = new ArrayList<>();
        list.forEach(x -> {
            CommentRepayVo vo = new CommentRepayVo();
            BeanUtils.copyProperties(x, vo);
            for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                if (x.getId().equals(apCommentRepayLike.getCommentRepayId())) {
                    vo.setOperation((short) 0);
                    break;
                }
            }
            resultList.add(vo);
        });
        return ResponseResult.okResult(resultList);
    }

    @Autowired
    private IWeMediaClient weMediaClient;

    /**
     * 保存回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveRepay(ArticleCommentDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getContent()) || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtil.getApUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();
        String name = userClient.getById(user.getId());
        return saveCommentRepay(dto, userId, name);
    }

    @Override
    public ResponseResult saveCommentRepay(ArticleCommentDto dto, Integer userId, String name) {
        //文本内容检测
        Map<String, Object> map = weMediaClient.handleSensitiveScan(dto.getContent());
        if (map.get("flag").equals(false)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, (String) map.get("msg"));
        }
        //保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(userId);
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setAuthorName(name);
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.save(apCommentRepay);

        //更新回复数量
        WmNewsComment apComment = mongoTemplate.findById(dto.getCommentId(), WmNewsComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 回复点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveRepayLike(ArticleCommentDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getApUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询该评论回复
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        //点赞
        if (apCommentRepay != null && dto.getOperation() == 0) {
            //更新评论点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
            //保存评论点赞数据
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentRepayLike);
        } else {
            //更新评论点赞数量
            apCommentRepay.setLikes(Math.max(apCommentRepay.getLikes() - 1, 0));
            mongoTemplate.save(apCommentRepay);
            //删除评论点赞
            Query query = Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
        //4.取消点赞
        Map<String, Object> result = new HashMap<>();
        result.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(result);
    }
}
